﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Configuration;
using System.Data.SqlClient;
using SHelper;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraWaitForm;
using System.IO;

namespace InvoiceImport
{
    public partial class ReportForm : DevExpress.XtraEditors.XtraForm
    {
        public ReportForm()
        {
            InitializeComponent();
        }

        string con = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        public string ServerText { get; set; }
        public MainFrm mf { get; set; }
        DataTable SRtable, CBtable, Table1;
        string sdate1 = "", edate1 = "", sdate2 = "", edate2 = "", ItemName1 = "", ItemName2 = "";
        //行号
        private void gv_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        //查询
        private void SelectData()
        {
            var wf = new SplashScreenManager(this, typeof(DemoWaitForm), true, true);//进程
            wf.ShowWaitForm();
            wf.SetWaitFormCaption("正在查询...");
            #region 查询条件赋值
            if (string.IsNullOrEmpty(ItemText.Text))
            {
                ItemName1 = ItemName2 = "";
            }
            else
            {
                ItemName1 = string.Format("and c.cItemName like '%{0}%'", ItemText.Text);
                ItemName2 = string.Format("and a.cItemName like '%{0}%'", ItemText.Text);
            }
            if (string.IsNullOrEmpty(Sdate.Text))
            {
                sdate1 = sdate2 = "";
            }
            else
            {
                sdate1 = string.Format("and d.dPBVDate>='{0}'", Sdate.Text);
                sdate2 = string.Format("and b.dDate>='{0}'", Sdate.Text);
            }
            if (string.IsNullOrEmpty(Edate.Text))
            {
                edate1 = edate2 = "";
            }
            else
            {
                edate1 = string.Format("and d.dPBVDate<='{0}'", Edate.Text);
                edate2 = string.Format("and b.dDate<='{0}'", Edate.Text);
            }
            #endregion
            #region 查询语句
            Table1 = SqlHelper.ExecuteDataTable(string.Format(@"(select x.aName as [部门],c.cItemName as [项目名称],d.dPBVDate as [发生日期],c.cInvCode as [存货编码],d.cexch_name as [币种],d.cExchRate as [汇率], c.iTaxRate as [税率],
            c.iPBVQuantity  as [成本数量],c.iOriMoney as[成本原币无税金额],c.iOriSum as [成本原币价税合计],c.iMoney [成本本币无税金额],c.iSum as [成本本币价税合计],
            0 as [收入数量],0 as[收入原币无税金额],0 as [收入原币价税合计],0 [收入本币无税金额],0 as [收入本币价税合计]
            from purbillvouchs as c left join purbillvouch  as d on c.PBVID=d.PBVID
            left join [UFSystem].dbo.AreaMapping as x on c.cInvCode=(x.[aCode])
            where c.citemname is not null and c.cItemName not like '%未定%' {4} {0} {1}
            union
            select y.aName as [部门],a.cItemName as [项目名称],b.dDate as [发生日期],a.cInvCode as [存货编码],b.cexch_name as [币种],b.iExchRate as [汇率], a.iTaxRate as [税率],
            0 as [成本数量],0 as[成本原币无税金额],0 as [成本原币价税合计],0 [成本本币无税金额],0 as [成本本币价税合计],
            a.iQuantity as [收入数量],a.iMoney as[收入原币无税金额],a.iSum as [收入原币价税合计],a.iNatMoney [收入本币无税金额],a.iNatSum as [收入本币价税合计]
            from salebillvouchs as a left join salebillvouch  as b on a.SBVID=b.SBVID
            left join [UFSystem].dbo.AreaMapping as y on a.cInvCode=(y.[aCode])
            where a.cItemName is not null and a.cItemName not like '%未定%' {5} {2} {3}
            ) order by [项目名称],[发生日期] ", sdate1, edate1, sdate2, edate2, ItemName1, ItemName2), con, new SqlParameter());
            #endregion
            #region 添加项目合计
            string tempItemNmae="";
            int r = Table1.Rows.Count;
            for (int i = 0; i < r; i++)
            {
                if (tempItemNmae != Table1.Rows[i]["项目名称"].ToString().Trim())
                {
                    tempItemNmae = Table1.Rows[i]["项目名称"].ToString().Trim();
                    DataRow dr = Table1.NewRow();
                    dr["部门"] = Table1.Rows[i]["部门"].ToString().Trim();
                    dr["项目名称"] = Table1.Rows[i]["项目名称"].ToString().Trim();
                    dr["存货编码"] = "合计";
                    dr["成本原币无税金额"] = GetSum(Table1.Select(string.Format("项目名称='{0}'", tempItemNmae)), "成本原币无税金额");
                    dr["成本原币价税合计"] = GetSum(Table1.Select(string.Format("项目名称='{0}'", tempItemNmae)), "成本原币价税合计");
                    dr["成本本币无税金额"] = GetSum(Table1.Select(string.Format("项目名称='{0}'", tempItemNmae)), "成本本币无税金额");
                    dr["成本本币价税合计"] = GetSum(Table1.Select(string.Format("项目名称='{0}'", tempItemNmae)), "成本本币价税合计");
                    dr["收入原币无税金额"] = GetSum(Table1.Select(string.Format("项目名称='{0}'", tempItemNmae)), "收入原币无税金额");
                    dr["收入原币价税合计"] = GetSum(Table1.Select(string.Format("项目名称='{0}'", tempItemNmae)), "收入原币价税合计");
                    dr["收入本币无税金额"] = GetSum(Table1.Select(string.Format("项目名称='{0}'", tempItemNmae)), "收入本币无税金额");
                    dr["收入本币价税合计"] = GetSum(Table1.Select(string.Format("项目名称='{0}'", tempItemNmae)), "收入本币价税合计");
                    Table1.Rows.Add(dr);
                }
            }
            #endregion
            #region 添加利润合计
            Table1.Columns.Add("原币无税利润", Type.GetType("System.Decimal"));
            Table1.Columns.Add("原币含税利润", Type.GetType("System.Decimal"));
            Table1.Columns.Add("本币无税利润", Type.GetType("System.Decimal"));
            Table1.Columns.Add("本币含税利润", Type.GetType("System.Decimal"));
            for (int i = 0; i < Table1.Rows.Count; i++)
            {
                Table1.Rows[i]["原币无税利润"] = Math.Round((double.Parse(Table1.Rows[i]["收入原币无税金额"].ToString()) - double.Parse(Table1.Rows[i]["成本原币无税金额"].ToString())), 2).ToString("0.00");
                Table1.Rows[i]["原币含税利润"] = Math.Round((double.Parse(Table1.Rows[i]["收入原币价税合计"].ToString()) - double.Parse(Table1.Rows[i]["成本原币价税合计"].ToString())), 2).ToString("0.00");
                Table1.Rows[i]["本币无税利润"] = Math.Round((double.Parse(Table1.Rows[i]["收入本币无税金额"].ToString()) - double.Parse(Table1.Rows[i]["成本本币无税金额"].ToString())), 2).ToString("0.00");
                Table1.Rows[i]["本币含税利润"] = Math.Round((double.Parse(Table1.Rows[i]["收入本币价税合计"].ToString()) - double.Parse(Table1.Rows[i]["成本本币价税合计"].ToString())), 2).ToString("0.00");
            }
            #endregion
            #region 添加总合计
            DataView dv = Table1.DefaultView;
            dv.Sort = "项目名称 Asc";
            DataTable Table2 = dv.ToTable();
            if (r > 0)
            {
                DataRow dr = Table2.NewRow();
                dr["存货编码"] = "总合计";
                dr["成本原币无税金额"] = GetSum(Table1.Select(""), "成本原币无税金额");
                dr["成本原币价税合计"] = GetSum(Table1.Select(""), "成本原币价税合计");
                dr["成本本币无税金额"] = GetSum(Table1.Select(""), "成本本币无税金额");
                dr["成本本币价税合计"] = GetSum(Table1.Select(""), "成本本币价税合计");
                dr["收入原币无税金额"] = GetSum(Table1.Select(""), "收入原币无税金额");
                dr["收入原币价税合计"] = GetSum(Table1.Select(""), "收入原币价税合计");
                dr["收入本币无税金额"] = GetSum(Table1.Select(""), "收入本币无税金额");
                dr["收入本币价税合计"] = GetSum(Table1.Select(""), "收入本币价税合计");
                dr["原币无税利润"] = GetSum(Table1.Select(""), "收入原币无税金额");
                dr["原币含税利润"] = GetSum(Table1.Select(""), "收入原币价税合计");
                dr["本币无税利润"] = GetSum(Table1.Select(""), "收入本币无税金额");
                dr["本币含税利润"] = GetSum(Table1.Select(""), "收入本币价税合计");
                Table2.Rows.Add(dr);
            }
            #endregion
            gc.DataSource = Table2;
            if (wf.IsSplashFormVisible) wf.CloseWaitForm();//关闭进程
        }
        //获取合计
        public string GetSum(DataRow[] drs, string ColumnName)
        {
            double sum = 0;
            foreach (var temp in drs)
            {
                try
                {
                    sum += double.Parse(temp[ColumnName].ToString());
                }
                catch { sum += 0; }
            }
            return Math.Round(sum, 2).ToString("0.00");
        }
        //加载
        private void ReportForm_Load(object sender, EventArgs e)
        {
            DateTime tempDate = DateTime.Today.AddMonths(-1);
            Sdate.DateTime = DateTime.Parse(tempDate.Year.ToString("0000") + "-" + tempDate.Month.ToString("00") + "-01");
            Edate.DateTime = DateTime.Parse(tempDate.Year.ToString("0000") + "-" + tempDate.Month.ToString("00") + "-" + DateTime.DaysInMonth(tempDate.Year, tempDate.Month).ToString("00"));
            con = con.Replace("UFDATA_999_2013", ServerText);
        }
        //查询按钮
        private void SelectBtn_Click(object sender, EventArgs e)
        {
            SelectData();
        }
        //回车查询
        private void ItemText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SelectData();
            }
        }
        //导出Excel
        private void ExPortBtn_Click(object sender, EventArgs e)
        {
            if (gv.RowCount < 1)
            {
                MessageBox.Show("没有需要导出的数据!", "提示");
                return;
            }
            SaveFileDialog dialog = new SaveFileDialog()
            {
                FileName = string.Format("收入成本报表{0}-{1}-{2}", DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day),
                Filter = "Execl 文件(*.xls)|*.xls|Execl 文件(*.xlsx)|*.xlsx"
            };
            FileInfo KGFileInfo = null;
            FileInfo KGFileInfo1 = null;
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            else
            {
                KGFileInfo = new FileInfo(dialog.FileName);
                KGFileInfo1 = new FileInfo(dialog.FileName);
            }
            try
            {
                switch (KGFileInfo.Extension.ToLower())
                {
                    case ".xls":
                        gv.ExportToXls(dialog.FileName);
                        break;
                    case ".xlsx":
                        gv.ExportToXlsx(dialog.FileName);
                        break;
                    default:
                        MessageBox.Show(string.Format("尚未支持的格式{0}", KGFileInfo.Extension), "提示");
                        return;
                }
                XtraMessageBox.Show("导出成功!", "提示");
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("导出失败!原因:" + ex, "提示");
            }
        }

        private void AreaSetting_Click(object sender, EventArgs e)
        {
            AreaSettingForm asf = new AreaSettingForm();
            asf.ShowDialog();
        }

        private void ReportForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            mf.Show();
        }
    }
}